﻿@using PMS.Web.FrontUI
@using PMS.Web.Models.Customers
@using PMS.Web.Models.Messages
@{
    Layout = "_AdminHomeLayout";
    var customerEmailSearchModel = ViewBag.CustomerEmailSearchModel as CustomerEmailSearchModel ?? null;
}
@model CustomerModel
@section CssStyles{
    <style type="text/css">
        .user-info-head img {
            width: 110px;
            height: 110px;
            border-radius: 50%;
        }

        .info-list-item {
            position: relative;
            padding-bottom: 8px;
        }

        .info-list-item i {
            float: left;
        }

        .info-list-item > p {
            margin-left: 30px;
        }

        .dash {
            border-bottom: 1px dashed #ccc;
            margin: 15px 0;
        }

        .layui-form-switch {
            margin-top: 6px;
            height: 25px;
        }

        .layui-form-item .layui-input-inline {
            width: 268px;
        }

        .layui-layer .layui-form-label {
            width: 95px;
        }
    </style>
}

<div class="layui-collapse">
    <div class="layui-colla-item">
        <h2 class="layui-colla-title">用户基本信息</h2>
        <div class="layui-colla-content layui-show">
            <div class="layui-fluid">
                <div class="layui-form layui-row">
                    <!-- 左 -->
                    <div class="layui-col-sm12 layui-col-md3 layui-col-md-offset1">
                        <div class="layui-card">
                            <div class="layui-card-body" style="padding: 25px;">
                                <div class="text-center layui-text">
                                    <div class="user-info-head" id="imgHead">
                                        <img alt="用户头像" src="@Model.AvatarImage.ImageUrl">
                                    </div>
                                    <h2 style="padding-top: 20px;">@(string.IsNullOrEmpty(Model.NickName) ? Model.DisplayName(m => m.NickName) : Model.NickName)</h2>
                                    <p style="padding-top: 8px;">@Html.HideEmail(Model.Email)</p>
                                    <p style="padding-top: 8px;">@Html.HideMobile(Model.Mobile)</p>
                                </div>
                                <div class="layui-text" style="padding-top: 30px;">
                                    <div class="info-list-item">
                                        <i class="layui-icon layui-icon-username"></i>
                                        <p>@(string.IsNullOrEmpty(Model.LoginName) ? Model.DisplayName(m => m.LoginName) : Model.LoginName)</p>
                                    </div>
                                    <div class="info-list-item">
                                        <i class="layui-icon @(Model.Gender == "男" ? "layui-icon-male" : "layui-icon-female")"></i>
                                        <p>@(string.IsNullOrEmpty(Model.Gender) ? Model.DisplayName(m => m.Gender) : Model.Gender)</p>
                                    </div>
                                    <div class="info-list-item">
                                        <i class="layui-icon layui-icon-gift"></i>
                                        <p>@(Model.DateOfBirth.HasValue ? Model.DateOfBirth.Value.ToString("yyyy-MM-dd") : Model.DisplayName(m => m.DateOfBirth))</p>
                                    </div>
                                    <div class="info-list-item">
                                        <i class="layui-icon layui-icon-user"></i>
                                        <p>@(string.IsNullOrEmpty(Model.CustomerRoleNames) ? Model.DisplayName(m => m.CustomerRoleNames) : Model.CustomerRoleNames)</p>
                                    </div>
                                </div>
                                <div class="dash"></div>
                                <div class="layui-text">
                                    <div class="info-list-item">
                                        <i class="layui-icon layui-icon-time"></i>
                                        <p>@(Model.LastActivityTime == null ? Model.DisplayName(m => m.LastActivityTime) : Model.LastActivityTime.ToString("yyyy-MM-dd HH:mm"))</p>
                                    </div>
                                    <div class="info-list-item">
                                        <i class="layui-icon layui-icon-location"></i>
                                        <p>@(string.IsNullOrEmpty(Model.LastLoginIpAddress) ? Model.DisplayName(m => m.LastLoginIpAddress) : Model.LastLoginIpAddress)</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 右 -->
                    <div class="layui-col-sm12 layui-col-md8">
                        <div class="layui-card">
                            <div class="layui-card-body">
                                <div class="user-info-form layui-text" style="padding-top: 25px;">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.Email)</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="@Model.NameOf(m => m.Email)" value="@(string.IsNullOrEmpty(Model.Email) ? "" : Html.HideEmail(Model.Email))" lay-verify="required|emailwhencreate" placeholder="请输入Email" autocomplete="off" class="layui-input" />
                                        </div>
                                        @if (string.IsNullOrEmpty(Model.Email))
                                        {//新用户注册
                                            <div class="layui-form-mid layui-word-aux">Email可用于账号登录，需保证唯一性</div>
                                        }
                                        else
                                        {
                                            <div class="layui-form-mid layui-word-aux">不可编辑,修改无效</div>
                                        }
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.Mobile)</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="@Model.NameOf(m => m.Mobile)" value="@(string.IsNullOrEmpty(Model.Mobile) ? "" : Html.HideMobile(Model.Mobile))" lay-verify="required|phonewhencreate" placeholder="请输入手机号码" autocomplete="off" class="layui-input" />
                                        </div>
                                        @if (string.IsNullOrEmpty(Model.Mobile))
                                        {//新用户注册
                                            <div class="layui-form-mid layui-word-aux">手机号可用于账号登录，需保证唯一性</div>
                                        }
                                        else
                                        {
                                            <div class="layui-form-mid layui-word-aux">不可编辑,修改无效</div>
                                        }
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.LoginName)</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="@Model.NameOf(m => m.LoginName)" value="@Model.LoginName" lay-verify="required" placeholder="以字母开头的字母数字组合，且长度为3-20位" autocomplete="off" class="layui-input" />
                                        </div>
                                        @if (string.IsNullOrEmpty(Model.LoginName))
                                        {//新用户注册
                                            <div class="layui-form-mid layui-word-aux">账号登录用于账号登录，需保证唯一性</div>
                                        }
                                        else
                                        {
                                            <div class="layui-form-mid layui-word-aux">不可编辑,修改无效</div>
                                        }
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.NickName)</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="@Model.NameOf(m => m.NickName)" value="@Model.NickName" lay-verify="required" placeholder="请输入用户昵称" autocomplete="off" class="layui-input" />
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.Gender)</label>
                                        <div class="layui-input-block">
                                            <input type="radio" name="@Model.NameOf(m => m.Gender)" value="男" title="男" @if (Model.Gender == "男") { <text> checked </text> }>
                                            <input type="radio" name="@Model.NameOf(m => m.Gender)" value="女" title="女" @if (Model.Gender == "女") { <text> checked </text> }>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.DateOfBirth)</label>
                                        <div class="layui-input-inline">
                                            <input type="text" id="birthDay" name="@Model.NameOf(m => m.DateOfBirth)" value="@(Model.DateOfBirth.HasValue ? Model.DateOfBirth.Value.ToString("yyyy-MM-dd") : "")" autocomplete="off" class="layui-input" />
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.DefaultAddress)</label>
                                        <div class="layui-input-inline">
                                            <div id="areaSelect"></div>
                                            <input type="text" name="@Model.NameOf(m => m.DefaultAddress)" value="@((Model.DefaultAddress?.Count ?? 0) > 0 ? (string.Join(",", Model.DefaultAddress)) : "")" autocomplete="off" class="layui-input layui-hide" />
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label"></label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="@Model.NameOf(m => m.DefaultAddressDetail)" value="@Model.DefaultAddressDetail" placeholder="请输入详细地址" autocomplete="off" class="layui-input" />
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.Password)</label>
                                        <div class="layui-input-inline">
                                            <input type="password" name="@Model.NameOf(m => m.Password)" value="" @if (Model.Id == 0) { <text> lay-verify="required" </text> } placeholder="请输入账户密码" autocomplete="off" class="layui-input" />
                                            <input type="text" class="layui-hide" name="@Model.NameOf(m => m.PasswordStrongLevel)" value="" />
                                        </div>
                                        <div class="layui-form-mid layui-word-aux">
                                            <input type="checkbox" name="@Model.DisplayName(m => m.AllowReSendingOfActivationMessage)" title="是否邮件通知用户" lay-skin="primary" lay-filter="changePasswordFilter" value="true" checked>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">@Model.DisplayName(m => m.IsActive)</label>
                                        <div class="layui-input-block">
                                            <input type="checkbox" name="@Model.NameOf(m => m.IsActive)" value="@Model.IsActive.ToString()" lay-filter="IsActiveSwitch" lay-skin="switch" lay-text="正常|锁定" @if (Model.IsActive) { <text> checked</text> }>
                                        </div>
                                    </div>
                                    <input type="text" name="@Model.NameOf(m => m.Id)" value="@Model.Id" class="layui-hide" />
                                    <div class="layui-form-item">
                                        <div class="layui-input-block">
                                            <button type="button" id="userInfoSubmitBtn" class="pear-btn pear-btn-primary pear-btn-sm" lay-filter="userInfoSubmit" lay-submit="">
                                                保存提交
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-colla-item">
        <h2 class="layui-colla-title">往来邮件</h2>
        <div class="layui-colla-content">
            <input type="text" id="gridPageSize" value="@customerEmailSearchModel.AvailablePageSizes" class="layui-hide" />
            <table id="pms-table" lay-filter="pms-table"></table>
        </div>
    </div>
</div>

@await Component.InvokeAsync("ModelValidateError")
<script type="text/html" id="EmailPageToolbarTpl">
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="OnSendEmail">
        <i class="layui-icon layui-icon-email"></i>
        发送邮件
    </button>
</script>
<script type="text/html" id="EmailIsActiveTpl">
    {{#  if(d.SendEmail.IsActive && d.SendEmail.DontSendBeforeDate != null){ }}
    <span class="layui-badge layui-bg-orange">延迟发送</span>
    {{#  } else if(!d.SendEmail.IsActive && d.SendEmail.SentOnTime != null) { }}
    <span class="layui-badge layui-bg-green">已发送</span>
    {{#  } else { }}
    <span class="layui-badge">待发送</span>
    {{#  } }}
</script>
<script type="text/html" id="SendEmailPopupFormTpl">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.Email)</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.NameOf(m => m.NickName)" value="@Model.NickName" required lay-verify="required" placeholder="请输入收件人称谓" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.Email)</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.NameOf(m => m.Email)" value="@Html.HideEmail(Model.Email)" readonly lay-verify="required" placeholder="请输入邮箱地址" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.SendEmail.DisplayName(m => m.Subject)</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.NameOf(m => m.SendEmail.Subject)" value="" lay-verify="required" placeholder="请输入邮件正文标题" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.SendEmail.DisplayName(m => m.Body)</label>
            <div class="layui-input-block">
                <textarea id="EmailContent" name="@Model.NameOf(m => m.SendEmail.Body)" class="layui-hide"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">@Model.SendEmail.DisplayName(m => m.SendImmediately)</label>
                <div class="layui-input-inline">
                    <input type="checkbox" name="@Model.NameOf(m => m.SendEmail.SendImmediately)" value="@Model.SendEmail.SendImmediately.ToString()" title="@Model.SendEmail.DisplayName(m => m.SendImmediately)"
                           lay-skin="primary" lay-filter="SendEmailNowCheck" @if(Model.SendEmail.SendImmediately) { <text> checked </text> } >
                </div>
            </div>

            <div class="layui-inline layui-hide">
                <label class="layui-form-label">@Model.SendEmail.DisplayName(m => m.DontSendBeforeDate)</label>
                <div class="layui-input-inline">
                    <input type="text" id="DontSendBeforeDate" name="@Model.NameOf(m => m.SendEmail.DontSendBeforeDate)" value="@(Model.SendEmail.DontSendBeforeDate.HasValue ? Model.SendEmail.DontSendBeforeDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))" autocomplete="off" class="layui-input" />
                </div>
            </div>
            
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" id="SendEmailPopupFormSubmitBtn" lay-submit lay-filter="SendEmailPopupFormSubmit">立即提交</button>
            </div>
        </div>
    </form>
</script>
@section Scripts{
    <script src="~/lib/ipicker/dist/iPicker.min.js" asp-append-version="true"></script>
    <script src="~/dist/js/utils/passwordstrength.min.js" asp-append-version="true"></script>
    <script type="text/javascript">
        layui.use(['jquery', 'form', 'element', 'lodash', 'laydate', 'http', 'button', 'laytpl', 'popup', 'table', 'Cookies', 'layedit', 'Base64'], function () {
            var $ = layui.jquery,
                form = layui.form,
                element = layui.element,
                lodash = layui.lodash,
                laydate = layui.laydate,
                http = layui.http,
                button = layui.button,
                laytpl = layui.laytpl,
                popup = layui.popup,
                table = layui.table,
                Cookies = layui.Cookies,
                layedit = layui.layedit,
                Base64 = layui.Base64;

            var userInfoPage = {
                getAreaJson: function () {
                    return new Promise(function (resolve) {
                        http.get(backendwebapiConfig.getareadatajson, null)
                            .then(function (response) {
                                if (response.state && response.state === 200) {
                                    resolve(response.data);
                                }
                            });
                    });
                },
                initPageComponent: function () {
                    var self = this;
                    //生日日期选择
                    laydate.render({
                        elem: '#birthDay'
                        , type: 'date'
                    });
                    //AreaSelect
                    iPicker.create("#areaSelect", {
                        theme: "cascader",
                        data: {
                            source: self.getAreaJson()
                        },
                        width: 268,
                        icon: "arrow-outline",
                        strict: true,
                        selected: lodash.split($("input[name=DefaultAddress]").val(), ","),
                        onSelect(code, name, map) {
                            $("input[name=DefaultAddress]").val(lodash.join(code, ','));
                        }
                    });
                    //当重置密码时是否邮件通知
                    form.on('checkbox(changePasswordFilter)', function (data) {
                        var $pwdInput = $("input[name=Password]");
                        if ($pwdInput.val().length <= 0) {
                            return false;
                        }
                        if (data.elem.checked) {
                            $(data.elem).val("true");
                        }
                    });
                    form.on('switch(IsActiveSwitch)', function (data) {
                        if (data.elem.checked) {
                            $(data.elem).val("true");
                        }
                    });

                    form.verify({
                        phonewhencreate: function (value, item) {
                            var customerId = PMSUtils.toNumber($("input[name=Id]").val());
                            if (customerId == 0) {
                                if (!PMSUtils.isValidMobile(value)) {
                                    return '请输入正确的手机号';
                                }
                            }
                        }
                        , emailwhencreate: function (value, item) {
                            var customerId = PMSUtils.toNumber($("input[name=Id]").val());
                            if (customerId == 0) {
                                if (!PMSUtils.isValidEmail(value)) {
                                    return '邮箱格式不正确';
                                }
                            }
                        }
                    });
                    form.on('submit(userInfoSubmit)', function (data) {
                        var submitUserInfo = function (userInfo) {
                            if (userInfo.DefaultAddress.length > 0 && PMSUtils.gettype(userInfo.DefaultAddress) === 'string') {
                                userInfo.DefaultAddress = lodash.split(userInfo.DefaultAddress, ',');
                            } else {
                                userInfo.DefaultAddress = null;
                            }
                            if (userInfo.Password.length <= 0 && userInfo.AllowReSendingOfActivationMessage) {
                                //勾选时 AllowReSendingOfActivationMessage 相应有值
                                //借用 Model.AllowReSendingOfActivationMessage 存储当修改账号密码时，是否发送重置密码邮件
                                //勾选重置账号密码但未输入重置密码，则无需发送邮件
                                userInfo.AllowReSendingOfActivationMessage = false;
                            } else if (userInfo.Password.length > 0) {
                                var strength = PasswordStrength.test(userInfo.LoginName, userInfo.Password);
                                if (strength.isGood()) {
                                    userInfo.PasswordStrongLevel = "Good";
                                } else if (strength.isStrong()) {
                                    userInfo.PasswordStrongLevel = "Strong";
                                } else {
                                    userInfo.PasswordStrongLevel = "Weak";
                                }
                            }

                            var loadbtn = null;
                            http.post(backendwebapiConfig.customeredit, userInfo,
                                function () { //beforeSend
                                    loadbtn = button.load({
                                        elem: '#userInfoSubmitBtn',
                                        time: 10000
                                    });
                                }
                            ).done(function (response) {
                                if (response.state && response.state === 200) {
                                    popup.success(response.message, function () {
                                        PMSUtils.closePopupWindow();
                                    });
                                }
                            }).fail(function (error) {
                                //For ModelValidation
                                if (error.status && error.status === 400) {
                                    var validator = error.responseJSON;
                                    if (validator.ErrorCode && validator.ErrorCode === "FluentValidationError") {
                                        var validateTpl = document.getElementById('validateResultTpl').innerHTML;
                                        laytpl(validateTpl).render(validator, function (html) {
                                            http.ajax.showError({
                                                message: '提示信息',
                                                details: html
                                            });
                                        });
                                        //标红校验错误的数据框
                                        layui.each(validator.Errors, function (index, item) {
                                            var inputField = item.ErrorField;
                                            $("input[name=" + inputField + "]").attr('failure', '');
                                        });
                                    }
                                }
                            }).always(function () {
                                loadbtn.stop(function () { });
                            });
                        };
                        var postData = data.field;
                        if (postData.Password.length > 0 && postData.Id > 0) {
                            layer.confirm('您确定要重置该账号密码吗?', { icon: 3, title: '提示' }, function (index) {
                                //do something
                                submitUserInfo(postData);
                                layer.close(index);
                            });
                            return false;
                        }

                        submitUserInfo(postData);
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                },
            };

            var emailPage = {
                getAuthToken: function () {
                    const cookieVal = Cookies.get(".PMS.SignInToken");
                    return cookieVal != null ? "Bearer " + cookieVal : "";
                },
                initPageComponent: function () {
                    var authToken = this.getAuthToken();
                    var reqHeader = null;
                    if (authToken.length > 0) {
                        reqHeader = { 'Authorization': authToken };
                    }
                    let availabePageSize = PMSUtils.parseToIntegerArray($("#gridPageSize").val());
                    var emailTblConfig = {
                        id: 'pms-table',
                        elem: '#pms-table',
                        method: 'post',
                        contentType: 'application/json;charset=UTF-8',
                        url: backendwebapiConfig.pagedemaillistbycustomer,
                        request: {
                            pageName: '@customerEmailSearchModel.NameOf(p => p.Page)', //页码的参数名称，默认：page
                            limitName: '@customerEmailSearchModel.NameOf(p => p.PageSize)' //每页数据量的参数名，默认：limit
                        },
                        where: {
                            '@customerEmailSearchModel.NameOf(p => p.CustomerId)': '@customerEmailSearchModel.CustomerId'
                        },
                        headers: reqHeader,
                        limits: availabePageSize,
                        limit:  @customerEmailSearchModel.PageSize,
                        skin: 'line',
                        toolbar: '#EmailPageToolbarTpl',
                        page: {
                            curr: 1
                        },
                        cols: [
                            [
                                { field: '@Model.NameOf(p => p.Email)', title: '@Model.DisplayName(m => m.Email)', width: 230 },
                                { field: '@Model.NameOf(p => p.NickName)', title: '@Model.DisplayName(m => m.NickName)', width: 160 },
                                {
                                    field: 'SendEmail.Subject', title: '@Model.SendEmail.DisplayName(m => m.Subject)', minWidth: 290
                                    , templet: function (d) {
                                        return '<span>' + d.SendEmail.Subject + '</span>';
                                    }
                                },
                                { field: 'SendEmail.IsActive', title: '@Model.SendEmail.DisplayName(m => m.IsActive)', width: 110, templet: '#EmailIsActiveTpl' },
                                {
                                    field: 'SendEmail.SentOnTime', title: '@Model.SendEmail.DisplayName(m => m.SentOnTime)', minWidth: 140
                                    , templet: function (d) {
                                        return '<span>' + d.SendEmail.SentOnTime + '</span>';
                                    }
                                },
                            ]
                        ],
                        error: function (e, msg) {
                            if (e.status === 401) { //UnAuthorized
                                var Error401 = http.ajax.defaultError401;
                                if (error.responseJSON) {
                                    if (error.responseJSON.error !== undefined) {
                                        Error401 = {
                                            message: error.responseJSON.error,
                                            details: error.responseJSON.error_description
                                        };
                                    }
                                }
                                http.ajax.showError(Error401);
                            }
                        },
                        parseData: function (res) {
                            return {
                                "code": res.state == 200 ? 0 : -1,     //解析接口状态
                                "msg": res.state == 200 ? "" : res.message,     //解析提示文本
                                "count": res.state == 200 ? res.data.RecordsTotal : 0, //解析数据长度
                                "data": res.state == 200 ? res.data.Data : null,   //解析数据列表
                            };
                        }
                    };
                    var emailTblIns = table.render(emailTblConfig);

                    table.on('toolbar(pms-table)', function (obj) {
                        if (obj.event === 'OnSendEmail') {
                            layer.open({
                                type: 1,
                                title: '发送邮件'
                                , content: $("#SendEmailPopupFormTpl")[0].innerHTML
                                , area: ['530px', '500px']
                                , resize: false
                                , success: function (layero, index) {
                                    var cid = $("input[name=Id]").val(),
                                        email = layero.find("input[name=Email]").val();
                                    if (cid === "0" || email.length <= 0) {
                                        popup.failure("用户未绑定邮箱,无法发送邮件", function () {
                                            layer.close(index);
                                        });
                                    } else {
                                        form.render('checkbox');
                                        laydate.render({
                                            elem: '#DontSendBeforeDate'
                                            , type: 'datetime'
                                            , min: 'nowTime' //计划发送时间为当前时间以后
                                            , max: 30        //计划发送时间最多从当前时间开始设置30天
                                            , btns: ['clear', 'confirm']
                                            , trigger: 'click'
                                        });
                                        //立即发送触发
                                        form.on('checkbox(SendEmailNowCheck)', function (data) {
                                            var $datePicker = $("#DontSendBeforeDate");
                                            if (!data.elem.checked) {
                                                $datePicker.parents(".layui-inline").removeClass("layui-hide");
                                            } else {
                                                $datePicker.parents(".layui-inline").addClass("layui-hide");
                                                $datePicker.val("");
                                            }
                                        });
                                        var editor = layedit.build('EmailContent', {
                                            height: 180 //设置编辑器高度
                                            , tool: [
                                                'strong' //加粗
                                                , 'italic' //斜体
                                                , 'underline' //下划线
                                                , 'del' //删除线
                                                , 'left' //左对齐
                                                , 'center' //居中对齐
                                                , 'right' //右对齐
                                                , 'link' //超链接
                                                , 'unlink' //清除链接
                                            ]
                                        });
                                        form.on('submit(SendEmailPopupFormSubmit)', function (data) {
                                            var emailData = data.field;
                                            emailData.Body = Base64.encode(layedit.getContent(editor));
                                            if (emailData.Body.length <= 0) {
                                                popup.failure("请填写待发送邮件内容");
                                                return false;
                                            }
                                            //CustomerModel Data Json
                                            var postData = {
                                                Id: cid,
                                                Email: email,
                                                NickName: emailData.NickName,
                                                SendEmail: {
                                                    Subject: emailData.Subject,
                                                    Body: emailData.Body,
                                                    SendImmediately: emailData.SendImmediately === undefined ? false : true,
                                                    DontSendBeforeDate: emailData.DontSendBeforeDate.length > 0 ? email.DontSendBeforeDate : null
                                                }
                                            };
                                            var loadbtn = null;
                                            http.post(backendwebapiConfig.sendcustomemailtocustomer, postData, function () { //beforeSend
                                                loadbtn = button.load({
                                                    elem: '#SendEmailPopupFormSubmitBtn',
                                                    time: 10000
                                                });
                                            }).done(function (response) {
                                                if (response.state && response.state === 200) {
                                                    popup.success(response.message, function () {
                                                        layer.close(index);
                                                    });
                                                }
                                            }).fail(function (error) {
                                                //For ModelValidation
                                                if (error.status && error.status === 400) {
                                                    var validator = error.responseJSON;
                                                    if (validator.ErrorCode && validator.ErrorCode === "FluentValidationError") {
                                                        var validateTpl = document.getElementById('validateResultTpl').innerHTML;
                                                        laytpl(validateTpl).render(validator, function (html) {
                                                            http.ajax.showError({
                                                                message: '提示信息',
                                                                details: html
                                                            });
                                                        });
                                                        //标红校验错误的数据框
                                                        layui.each(validator.Errors, function (index, item) {
                                                            var inputField = item.ErrorField;
                                                            layero.find("input[name=" + inputField + "]").attr('failure', '');
                                                        });
                                                    }
                                                }
                                            }).always(function () {
                                                loadbtn.stop(function () { });
                                            });
                                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                                        });
                                    }
                                }
                                , end: function () {
                                    emailTblIns.reload(emailTblConfig, true);
                                }
                            });
                        }
                    });
                },
            };

            userInfoPage.initPageComponent();
            emailPage.initPageComponent();
        });
    </script>
}
